<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      ref="crud"
      v-model="form"
      v-model:page="page"
      :permission="permissionList"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template #menu-right>
        <el-button
          type="success"
          icon="el-icon-upload"
          v-if="userCode && userCode.length == 2"
          @click="handleImport"
          >导入
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-circle-plus"
          v-if="userCode && userCode.length == 2"
          @click="handleCreate"
          >新建
        </el-button>
      </template>
      <template #menu="scope">
        <el-button type="primary" text icon="el-icon-view" @click.stop="handleInfo(scope.row)"
          >详情
        </el-button>
        <el-button
          type="primary"
          text
          icon="el-icon-edit"
          v-if="userCode && userCode.length == 2 && scope.row.isImport == 1 && scope.row.isUp == 1"
          @click.stop="editInfo(scope.row)"
          >编辑
        </el-button>
        <el-button
          type="primary"
          text
          icon="el-icon-edit"
          v-if="
            userCode && userCode.length == 2 && scope.row.endFlag == 2 && scope.row.commonRate == ''
          "
          @click.stop="RatwInfo(scope.row)"
          >综合评价
        </el-button>
      </template>
      <template #attachList="{ row }">
        <el-tag v-for="(tag, index) in row.attachList" :key="index">
          {{ tag.name }}
        </el-tag>
      </template>
    </avue-crud>
  </basic-container>

  <el-dialog v-model="dialogVisible" width="800px">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="详情" name="first">
        <div class="d_box">
          <div class="d_row">
            <p class="d_p">项目名称：</p>
            {{ rowData.projectName }}
          </div>
          <div class="d_row">
            <p class="d_p">项目地址：</p>
            {{ rowData.projectAddr }}
          </div>
          <div class="d_row">
            <p class="d_p">项目有效时间：</p>
            {{ rowData.projectStartTime + ' - ' + rowData.projectEndTime }}
          </div>
          <div class="d_row">
            <p class="d_p">项目类型：</p>
            {{ changeProjeType(rowData.projectType) }}
          </div>
          <div class="d_row">
            <p class="d_p">帮扶方式：</p>
            {{ chantgeraiseType(rowData.raiseType) }}
          </div>
          <div class="d_row">
            <p class="d_p">发起人：</p>
            {{ rowData.creator }}
          </div>
          <div class="d_row">
            <p class="d_p">行政区域：</p>
            {{ rowData.adnm }}
          </div>
          <div class="d_row">
            <p class="d_p">是否上架：</p>
            {{ isUpType }}
          </div>
          <div class="d_row">
            <p class="d_p">是否审核：</p>
            {{ statusType }}
          </div>
          <div class="d_row">
            <p class="d_p">附件：</p>
            <div class="d_cloum">
              <a :href="item.link" v-for="item in rowData.attachList" :key="item.id">{{
                item.originalName
              }}</a>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="项目认领情况" name="second">
        <!-- 使用表格展示项目认领情况 -->
        <div class="d_box" v-for="(item, index) in assisetData" :key="index">
          <div class="d_row">
            <p class="d_p">认领人：</p>
            {{ rowData.creator }}
          </div>
          <div class="d_row">
            <p class="d_p">认领项目：</p>
            {{ item.projectBase.projectName }}
          </div>
          <div class="d_row">
            <p class="d_p">认领时间：</p>
            {{ item.createTime }}
          </div>
          <div class="d_row">
            <p class="d_p">项目描述：</p>
            {{ item.projectBase.projectRemark }}
          </div>

          <div class="d_row">
            <p class="d_p">附件：</p>
            <div class="d_cloum">
              <a :href="item.link" v-for="item in rowData.attachList" :key="item.id">{{
                item.originalName
              }}</a>
            </div>
          </div>
          <div class="divider"></div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="项目进展" name="third">
        <!-- 使用表格展示项目进展 -->
        <div class="d_box" v-for="(item, index) in progressData" :key="index">
          <div class="d_row">
            <p class="d_p">项目进展描述：</p>
            {{ item.remark }}
          </div>
          <div class="d_row">
            <p class="d_p">创建时间：</p>
            {{ item.createTime }}
          </div>
          <div class="divider"></div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="评价情况" name="fourth">
        <!-- 使用表格展示评价情况 -->
        <div class="d_box" v-for="(item, index) in RateList" :key="index">
          <div class="d_row">
            <p class="d_p">评价人：</p>
            {{ item.creator }}
          </div>
          <div class="d_row">
            <p class="d_p">评价内容：</p>
            {{ item.remark }}
          </div>
          <div class="d_row">
            <p class="d_p">评分等级：</p>
            <el-rate v-model="item.rate"></el-rate>
          </div>
          <div class="d_row">
            <p class="d_p">评价时间：</p>
            {{ item.createTime }}
          </div>
          <div class="divider"></div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>

  <el-dialog title="数据导入" append-to-body v-model="excelBox" width="555px">
    <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter">
      <template #excelTemplate>
        <el-button type="primary" @click="handleTemplate">
          点击下载<i class="el-icon-download el-icon--right"></i>
        </el-button>
      </template>
    </avue-form>
  </el-dialog>

  <el-dialog v-model="dialogTableVisible" :title="popUptitle" width="800px">
    <avue-form
      :option="editOption"
      :upload-after="editUploadAfter"
      v-model="gridData"
      @submit="saveEdit"
      :loading="editLoading"
    >
      <!-- 封面列表 -->
      <template #attachLinkScope>
        <img class="attchImg" v-if="gridData.attachLink" :src="gridData.attachLink" alt="" />
        <el-icon
          v-if="gridData.attachLink"
          @click="deleteAttcheLink()"
          class="deleteIcon"
          :size="20"
        >
          <Delete />
        </el-icon>
      </template>

      <template #attachList>
        <!-- 附件列表 -->
        <div class="attchListStyle" v-for="(item, index) in editAttchList" :key="item">
          <span>{{ item.originalName }}</span>
          <el-icon @click="deleteAttcheItem(index)" class="deleteIcon" :size="20">
            <Delete />
          </el-icon>
        </div>
      </template>
    </avue-form>
  </el-dialog>
</template>

<script>
import {
  projectList,
  update,
  projectClaim,
  projectProgress,
  projectEvaluate,
} from '@/api/project/pageList';
import { mapGetters } from 'vuex';


export default {
  data() {
    return {
      form: {},
      selectionList: [],
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      option: {
        indexLabel: '序号',
        indexWidth: '70',
        height: 'auto',
        calcHeight: 32,
        tip: false,
        searchShow: true,
        searchMenuSpan: 3,
        // searchMenuPosition: right,
        menu: true,
        menuRight: true,
        border: true,
        index: true,
        selection: true,
        viewBtn: true,
        dialogClickModal: false,
        addBtn: false,
        header: true,
        delBtn: false,
        column: [
          {
            label: '项目名称',
            prop: 'projectName',
            search: true,
            slot: true,
          },
          {
            label: '发起人',
            prop: 'creator',
          },
          {
            label: '行政区域',
            prop: 'adnm',
            disabled: true,
          },
          {
            label: '行政区域',
            prop: 'adcd',
            disabled: true,
            search: true,
            hide: true,
            display: false,
            type: 'cascader',
            checkStrictly: true,
            dicUrl: '/blade-system/region/lazy-tree',
            dicMethod: 'get',
            dicFormatter: res => {
              // 只返回江西省(id: 36)的数据
              return res.data.filter(item => item.id === '36');
            },
            dicQuery: {
              code: '36',
            },
            props: {
              label: 'title',
              value: 'id',
              children: 'children',
            },
          },
          {
            label: '项目地址',
            prop: 'projectAddr',
          },
          {
            label: '是否上架',
            prop: 'isUp',
            search: true,
            type: 'select',
            props: {
              label: 'name',
              value: 'value',
            },
            dicData: [
              { name: '待上架', value: 1 },
              { name: '已上架', value: 2 },
              { name: '已下架', value: 3 },
            ],
          },
          {
            label: '是否审核',
            prop: 'status',
            search: true,
            type: 'select',
            props: {
              label: 'name',
              value: 'value',
            },
            dicData: [
              { name: '待审核', value: 1 },
              { name: '审核通过', value: 2 },
              { name: '审核不通过', value: 3 },
            ],
          },
          {
            label: '项目有效开始时间',
            prop: 'projectStartTime',
          },
          {
            label: '项目类型',
            prop: 'projectType',
            search: false,
            type: 'select',
            props: {
              label: 'name',
              value: 'value',
            },
            dicData: [
              { name: '功能设施援建', value: 1 },
              { name: '扶弱济困救助', value: 2 },
              { name: '专业技术服务', value: 3 },
              { name: '人员赋能培训', value: 4 },
              { name: '就业产业扶持', value: 5 },
              { name: '产品消费帮扶', value: 6 },
              { name: '其他', value: 7 },
            ],
          },
          {
            label: '项目描述',
            prop: 'projectRemark',
          },
        ],
      },
      data: [],
      dialogVisible: false,
      rowData: {},
      excelBox: false,
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '模板上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '模板上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data',
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: '/blade-project/base/importProjectBase',
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          },
        ],
      },
      editOption: {
        labelWidth: '150',
        column: [
          {
            label: '项目名称',
            prop: 'projectName',
            span: 24,
            rules: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
          },
          {
            label: '行政区域',
            prop: 'adcd',
            type: 'cascader',
            checkStrictly: true,
            dicUrl: '/blade-system/region/lazy-tree',
            dicMethod: 'get',
            dicFormatter: res => {
              // 只返回江西省(id: 36)的数据
              return res.data.filter(item => item.id === '36');
            },
            dicQuery: {
              code: '36',
            },
            props: {
              label: 'title',
              value: 'id',
              children: 'children',
            },
          },
          {
            label: '项目地址',
            prop: 'projectAddr',
            span: 24,
            type: 'textarea',
            rules: [{ required: true, message: '请输入项目地址', trigger: 'blur' }],
          },
          {
            label: '发起人',
            prop: 'creator',
            span: 24,
            rules: [{ required: true, message: '请输入发起人', trigger: 'blur' }],
          },
          {
            label: '联系方式',
            prop: 'tel',
            span: 24,
            rules: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
          },
          {
            label: '项目开始时间',
            prop: 'projectStartTime',
            span: 24,
            type: 'date',
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
            range: true,
            rules: [{ required: true, message: '请选择项目有效时间', trigger: 'blur' }],
          },
          {
            label: '项目结束时间',
            prop: 'projectEndTime',
            span: 24,
            type: 'date',
            range: true,
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
            rules: [{ required: true, message: '请选择项目有效时间', trigger: 'blur' }],
          },
          {
            label: '项目类型',
            prop: 'projectType',
            span: 24,
            type: 'select',
            props: {
              label: 'name',
              value: 'value',
            },
            dicData: [
              { name: '功能设施援建', value: 1 },
              { name: '扶弱济困救助', value: 2 },
              { name: '专业技术服务', value: 3 },
              { name: '人员赋能培训', value: 4 },
              { name: '就业产业扶持', value: 5 },
              { name: '产品消费帮扶', value: 6 },
              { name: '其他', value: 7 },
            ],
          },
          {
            label: '帮扶方式',
            prop: 'raiseType',
            span: 24,
            type: 'select',
            props: {
              label: 'name',
              value: 'value',
            },
            dicData: [
              { name: '资金', value: 1 },
              { name: '物品', value: 2 },
              { name: '技术', value: 3 },
              { name: '服务', value: 4 },
              { name: '其他', value: 5 },
            ],
          },
          {
            label: '项目描述',
            prop: 'projectRemark',
            span: 24,
            type: 'textarea',
            formatter: val => {
              if (!val) return '';
              return val
                .replace(/&quot;/g, '"')
                .replace(/&apos;/g, "'")
                .replace(/&amp;/g, '&');
            },
            rules: [{ required: true, message: '请输入项目描述', trigger: 'blur' }],
          },
          {
            label: '封面上传',
            prop: 'attachLink',
            type: 'upload',
            drag: true,
            loadText: '封面上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data',
            },
            accept: '',
            action: '/blade-resource/oss/endpoint/put-file-attach',
          },
          {
            label: '',
            prop: 'attachLinkScope',
            formslot: true,
            span: 24,
          },

          {
            label: '文件上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '文件上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data',
            },
            accept: '',
            action: '/blade-resource/oss/endpoint/put-file-attach',
          },
          {
            label: '',
            prop: 'attachList',
            formslot: true,
            span: 24,
          },
        ],
      },
      editLoading: false,
      activeName: 'first',
      assisetData: [],
      progressData: [],
      RateList: [],
      userCode: '',
      dialogTableVisible: false,
      gridData: [],
      editAttchList: [],
      attchLinkImage: '',
      popUptitle: '',
     
    };
  },
  computed: {
    ...mapGetters(['userInfo', 'permission']),
    permissionList() {
      return {
        addBtn: false,
        viewBtn: false,
        delBtn: true,
        editBtn: false,
      };
    },
    pType() {
      if (this.rowData.projectType) {
        switch (this.rowData.projectType) {
          case 1:
            return '灾难救助';
          case 2:
            return '募集救助';
          case 3:
            return '其他';
          default:
            return '';
        }
      } else {
        return '';
      }
    },
    isUpType() {
      switch (this.rowData.isUp) {
        case 1:
          return '待上架';
        case 2:
          return '已上架';
        case 3:
          return '已下架';
        default:
          return '';
      }
    },
    statusType() {
      switch (this.rowData.status) {
        case 1:
          return '待审核';
        case 2:
          return '审核通过';
        case 3:
          return '审核不通过';
        default:
          return '';
      }
    },
  },


  methods: {
    deleteAttcheLink() {
      this.gridData.attachLink = '';
    },
    editUploadAfter(res, done, loading, column) {
      if (column.prop == 'attachLink') {
        this.gridData.attachLink = res.link;
        done();
      } else {
        this.editAttchList.push(res);
        done();
      }
    },

    deleteAttcheItem(index) {
      this.editAttchList.splice(index, 1);
    },
    chantgeraiseType(num) {
      let rasieList = [
        { name: '资金', value: 1 },
        { name: '物品', value: 2 },
        { name: '技术', value: 3 },
        { name: '服务', value: 4 },
        { name: '其他', value: 5 },
      ];
      let result = '';
      rasieList.forEach(element => {
        if (element.value == num) {
          result = element.name;
        }
      });
      return result;
    },

    changeProjeType(num) {
      let rasieList = [
        { name: '功能设施援建', value: 1 },
        { name: '扶弱济困救助', value: 2 },
        { name: '专业技术服务', value: 3 },
        { name: '人员赋能培训', value: 4 },
        { name: '就业产业扶持', value: 5 },
        { name: '产品消费帮扶', value: 6 },
        { name: '其他', value: 7 },
      ];
      let result = '';
      rasieList.forEach(element => {
        if (element.value == num) {
          result = element.name;
        }
      });
      return result;
    },

    // 新建
    handleCreate() {
      for (const key in this.gridData) {
        this.gridData[key] = '';
      }
      this.popUptitle = '新建项目';
      this.gridData.attachLink = '';
      this.editAttchList = [];
      this.dialogTableVisible = true;
    },

    saveEdit(res, done) {
      let attachId = this.editAttchList.map(item => item.attachId || item.id).join(',');
      if (Array.isArray(this.gridData.adcd)) {
        this.gridData.adcd = this.gridData.adcd[this.gridData.adcd.length - 1];
      } else if (this.gridData.adcd.includes(',')) {
        this.gridData.adcd =
          this.gridData.adcd.split(',')[this.gridData.adcd.split(',').length - 1];
      } else {
        this.gridData.adcd = this.gridData.adcd;
      }
      let params = {
        id: this.gridData.id,
        projectRemark: this.gridData.projectRemark,
        projectAddr: this.gridData.projectAddr,
        projectName: this.gridData.projectName,
        projectStartTime: this.gridData.projectStartTime,
        projectEndTime: this.gridData.projectEndTime,
        projectType: this.gridData.projectType,
        raiseType: this.gridData.raiseType,
        tel: this.gridData.tel,
        creator: this.gridData.creator,
        adcd: this.gridData.adcd,
        projectAddr: this.gridData.projectAddr,
        attachLink: this.gridData.attachLink,
        attachId,
      };
      if (this.popUptitle == '新建项目') {
        params.isUp = 1;
        params.prepareStatus = 2;
        params.status = 2;
        params.isImport = 1;
        params.creator = '省级用户';
      }

      update(params).then(res => {
        this.$message({
          type: 'success',
          message: res.data.msg,
        });
        this.dialogTableVisible = false;
        this.editLoading = false;
        this.onLoad(this.page);
        done();
      });
    },
    convertAdcdToArray(code) {
      if (Array.isArray(code)) return code;
      // 确保code是字符串类型
      code = String(code);
      if (code.length == 2) {
        return [code];
      }
      if (code.length == 4) {
        return [code.substring(0, 2), code];
      }
      if (code.length == 6) {
        return [code.substring(0, 2), code.substring(0, 4), code];
      }
    },
    // 编辑
    editInfo(row) {
      this.popUptitle = '编辑项目';
      this.gridData = row;
      this.gridData.adcd = this.convertAdcdToArray(this.gridData.adcd);
      this.editAttchList = row.attachList || [];
      this.dialogTableVisible = true;
    },
    // 综合评价
    RatwInfo(row) {
      this.$prompt('请输入综合评价', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputErrorMessage: '请输入综合评价',
      })
        .then(({ value }) => {
          update({ id: row.id, commonRate: value }).then(res => {
            this.$message({
              type: 'success',
              message: res.data.msg,
            });
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消评价',
          });
        });
    },
    handleImport() {
      this.excelBox = true;
    },
    uploadAfter(res, done, loading, column) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    handleTemplate() {
      window.open(`/000000-zhuli/upload/20250214/9de39c0fc7dac70d8c1fa980b3b28776.xlsx`);
    },

    handleInfo(row) {
      this.rowData = row;
      // 请求项目认领情况
      projectClaim(1, 1000, { projectBaseId: row.id, status: 3 }).then(res => {
        this.assisetData = res.data.data.records;
      });
      // 项目进展
      projectProgress(1, 1000, { projectBaseId: row.id }).then(res => {
        this.progressData = res.data.data.records;
      });
      // 项目评价
      projectEvaluate(1, 1000, { projectBaseId: row.id }).then(res => {
        this.RateList = res.data.data.records;
      });
      this.dialogVisible = true;
    },

    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      if (params.adcd) {
        let arr = params.adcd[params.adcd.length - 1];
        params.adcd = arr;
      }
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      projectList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.userCode = res.data.msg;
        this.loading = false;
        this.selectionClear();
      });
    },
  },
};
</script>

<style scoped lang="scss">
.d_box {
  padding: 0 20px;
  box-sizing: border-box;
  .d_row {
    display: flex;
    align-items: flex-start;
    margin: 18px 0;
    // flex-wrap: wrap;
    .d_p {
      width: 100px;
      margin: 0;
    }
    .d_cloum {
      display: block;
      flex-direction: column;
      a {
        display: block;
        margin-bottom: 8px;
        color: #2196f3;
      }
    }
  }
  .foot_box {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin: 20px 0;
  }
}

::v-deep .avue-crud__right {
  .is-circle {
    display: none;
  }
}
.divider {
  border-bottom: 1px solid #e0e0e0;
  margin: 20px 0;
}

.d_box {
  padding: 0 20px;
  box-sizing: border-box;
  .d_row {
    display: flex;
    align-items: flex-start;
    margin: 18px 0;
    // flex-wrap: wrap;
    .d_p {
      width: 100px;
      margin: 0;
    }
    .d_cloum {
      display: block;
      flex-direction: column;
      a {
        display: block;
        margin-bottom: 8px;
        color: #2196f3;
      }
    }
  }
  .foot_box {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin: 20px 0;
  }
}

::v-deep .avue-crud__right {
  .is-circle {
    display: none;
  }
}
.divider {
  border-bottom: 1px solid #e0e0e0;
  margin: 20px 0;
}

.el-input {
  width: 100%;
  .el-input__inner {
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    padding: 10px;
    font-size: 14px;
  }
  .el-textarea__inner {
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    padding: 10px;
    font-size: 14px;
  }
}
.attchListStyle {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 10px;
}
.deleteIcon {
  margin-left: 10px;
  cursor: pointer;
  color: #ff0000;
}
.attchImg {
  width: 100px;
  height: 100px;
}
</style>
